// 一元线性回归
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <vector>

using namespace std;

struct Data
{
    double CRIM;    // 人均犯罪率
    double ZN;      // 住宅用地所占比例
    double INDUS;   // 城镇非商业用地的比例
    double CHAS;    // 是否临近查尔斯河, 0 or 1
    double NOX;     // 一氧化氮浓度
    double RM;      // 住宅平均房间数
    double AGE;     // 1940年之前建成的自用房屋比例
    double DIS;     // 到波士顿5个中心区域的加权距离
    double RAD;     // 距离高速公路的便利指数
    double TAX;     // 每10000美元的全值财产税率
    double PTRATIO; // 城镇师生比例
    double B;       // 1000(Bk-0.63)^2, 其中Bk指代城镇中黑人的比例
    double LSTAT;   // 低收入人群的比例
    double MEDV;    // 平均房价
};

struct Data houses[507];
double xs[507][14];
double ys[507];
double bs[14];

int dataNum;
double a, b;
double sumXY;
double sumX;
double sumY;
double sumXX;

bool Inputs()
{
    string fname = "C:\\dev\\hduhomeworks\\cpp\\PD_Practice\\housing.txt";
    fstream f;
    f.open(fname, ios::in);
    int i = 0;
    if (f.is_open())
    {
        while (!f.eof())
        {
            f >> houses[i].CRIM >> houses[i].ZN >> houses[i].INDUS >> houses[i].CHAS >>
                houses[i].NOX >> houses[i].RM >> houses[i].AGE >> houses[i].DIS >> houses[i].RAD >>
                houses[i].TAX >> houses[i].PTRATIO >> houses[i].B >> houses[i].LSTAT >> houses[i].MEDV;
            // cout << houses[i].MEDV << endl;
            i++;
        }
        dataNum = i;
        cout << "已读取数据 " << dataNum << " 项" << endl;
        return true;
    }
    else
    {
        return false;
    }
}

void Init()
{
    a=b=sumXY=sumX=sumY=sumXX=0;
    /*
    for (int i = 0; i < dataNum; i++)
    {
        xs[i][0] = 1;
        xs[i][1] = houses[i].AGE;
        xs[i][2] = houses[i].B;
        xs[i][3] = houses[i].CHAS;
        xs[i][4] = houses[i].CRIM;
        xs[i][5] = houses[i].DIS;
        xs[i][6] = houses[i].INDUS;
        xs[i][7] = houses[i].LSTAT;
        xs[i][8] = houses[i].ZN;
        xs[i][9] = houses[i].NOX;
        xs[i][10] = houses[i].PTRATIO;
        xs[i][11] = houses[i].RAD;
        xs[i][12] = houses[i].RM;
        xs[i][13] = houses[i].TAX;
        ys[i] = houses[i].MEDV;
    }
    */
}

void LineReg(){
    for(int i=0; i<dataNum; i++){
        sumXY += houses[i].RM * houses[i].MEDV;
        sumX += houses[i].RM;
        sumY += houses[i].MEDV;
        sumXX += houses[i].RM * houses[i].MEDV;
    }
    b = (sumXY * dataNum - sumX * sumY)/ (sumXX * dataNum - sumX * sumX);
    a = sumY/dataNum - b*sumX / dataNum;
    cout << "Y= " << b << " X+ " << a << endl;
}

void Output()
{
    double x;
    double y;
    cout << "Enter some number" << endl;
    cin >> x;
    y = a + b * x;
    cout << "Expecting price to be " << y << endl;
}

int main()
{
    Inputs();
    Init();
    LineReg();
    Output();
    system("pause");
    return 0;
}